package cn.semes.org.service.impl;

import cn.semes.basic.service.impl.BaseServiceImpl;
import cn.semes.basic.util.MD5Utils;
import cn.semes.basic.util.PageList;
import cn.semes.basic.util.StrUtils;
import cn.semes.org.domain.Employee;
import cn.semes.org.mapper.EmployeeMapper;
//import cn.semes.org.query.EmployeeQuery;
import cn.semes.org.query.DepartmentQuery;
import cn.semes.org.service.IEmployeeService;
import cn.semes.user.domain.Logininfo;
import cn.semes.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void add(Employee employee) {
        // 给颜值随机赋值32位
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        // 设置默认密码
        if (employee.getPassword() == null) {
            employee.setPassword("123456");
        }
        // 密码加密 方式为颜值加上密码
        employee.setPassword(salt + employee.getPassword());

        // 存入logininfo表中
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);

        // 将login的id赋值给employee的logininfoId，然后添加到表中
        logininfoMapper.add(logininfo);
        employee.setLogininfoId(logininfo.getId());
        super.add(employee);
    }

    @Override
    public void update(Employee employee) {

        // 获取数据到logininfo，并赋值上id
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setId(employee.getLogininfoId());

        // 将login的id赋值给employee的logininfoId，然后添加到表中
        logininfoMapper.update(logininfo);
        super.update(employee);

    }

    @Override
    public void delete(Long id) {
        // 查找这个employee中的Logininfo的id，根据id删除
        Employee byId = employeeMapper.findById(id);
        logininfoMapper.delete(byId.getLogininfoId());

        // 删除employee
        super.delete(id);

    }
}
